package moni.anyou.com.view.view.my;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;

import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.bean.response.base.ResTeamBean;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.view.LogOut;
import moni.anyou.com.view.view.TeamDetailActivity;
import moni.anyou.com.view.view.team.adapter.TeamRecycleAdapter;
import moni.anyou.com.view.widget.NetProgressWindowDialog;

public class MyTeamActivity extends BaseActivity implements View.OnClickListener{
    private static int Fresh = 1;
    private static int LoadMore = 2;
    private NetProgressWindowDialog window;
    private SHSwipeRefreshLayout swipeRefreshLayout;
    private TeamRecycleAdapter mTeamRecycleAdapter;
    List<ResTeamBean.TeamBean> mTeamArray;
    private boolean isVisible = false;
    private RecyclerView rvTeam;
    private int pageSize = 12;
    private int pageNo = 1;
    private int totalCount;
    private String keyword = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leader_detail);
        initState();
        initWindow();
        init();
        LogOut.getInstance().addActivity(this);
    }
    @Override
    public void initView() {
        super.initView();
        initTitle();
        initSwipeRefreshLayout();
        window = new NetProgressWindowDialog(mBaseActivity);
        tvTitle.setText("我的行程");
        rvTeam = (RecyclerView) findViewById(R.id.rv_team);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvTeam.setLayoutManager(linearLayoutManager);
        mTeamArray = new ArrayList<>();
        mTeamRecycleAdapter = new TeamRecycleAdapter(this);
        rvTeam.setAdapter(mTeamRecycleAdapter);
        mTeamRecycleAdapter.setmOnItemClickListener(new TeamRecycleAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, ResTeamBean.TeamBean data) {
                Intent i = new Intent();
                i.putExtra("teamID", data.teamID);
                i.setClass(mBaseActivity, TeamDetailActivity.class);
                startActivity(i);
            }
        });
    }
    @Override
    public void setData() {
        super.setData();
        if (isVisible) {
            getData(1);
        }
    }
    public void onResume() {
        super.onResume();
        getData(1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:
                onBack();
                break;
        }
    }

    @Override
    public void setAction() {
        super.setAction();
        ivBack.setOnClickListener(this);
    }

    private void initSwipeRefreshLayout() {
        swipeRefreshLayout = (SHSwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View view = inflater.inflate(R.layout.refresh_view, null);
        final TextView textView = (TextView) view.findViewById(R.id.title);
        swipeRefreshLayout.setFooterView(view);
        swipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData(1);
            }

            @Override
            public void onLoading() {

                if (pageNo * pageSize < totalCount) {
                    pageNo++;
                    getData(2);
                } else {
                    swipeRefreshLayout.finishLoadmore();
                }
            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                    case SHSwipeRefreshLayout.START:
                        swipeRefreshLayout.setLoaderViewText("");
                        break;
                }
            }

            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        textView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        textView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        textView.setText("正在加载...");
                        break;
                }
            }
        });
    }
    public void getData(final int Type) {
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        //String cmdPara = new ReqLiveBean("16", SysConfig.uid, SysConfig.token, "" + pageNo, "" + pageSize, "babylive").ToJsonString();
        String cmdPara = "{\"cmd\":\"9\",\"uid\":\"" + SysConfig.uid + "\",\"token\":\"" + SysConfig.token +"\",\"isleader\":\"0\",\"pageno\":\"" + pageNo + "\",\"pagesize\":\"" + pageSize  +"\",\"keyword\":\"" + keyword + "\"}";
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                try {
                    JSONObject jsonObject = new JSONObject(t);
                    //Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        totalCount = jsonObject.getInt("totalCount");
                        ResTeamBean temp = new Gson().fromJson(t, ResTeamBean.class);
                        switch (Type) {
                            case 1:
                                swipeRefreshLayout.finishRefresh();
                                mTeamRecycleAdapter.setDatas(temp.getList());
                                break;
                            case 2:
                                swipeRefreshLayout.finishLoadmore();
                                mTeamRecycleAdapter.addDatas(temp.getList());
                                break;
                        }
                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity, result);
                        }
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show();
                    swipeRefreshLayout.finishRefresh();
                    swipeRefreshLayout.finishLoadmore();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                swipeRefreshLayout.finishRefresh();
                swipeRefreshLayout.finishLoadmore();
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
                window.closeWindow();
            }
        });


    }

    //手机高版本样式
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    private SystemBarTintManager tintManager;
    //手机高版本样式
    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.parseColor("#FEC600"));

            tintManager.setStatusBarTintEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(),
                        Color.TRANSPARENT);
            } catch (Exception e) {
            }
        }

    }
}
